package com.lwh.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.lwh.dao.UserMapper;
import com.lwh.entity.User;
import com.lwh.service.UserService;
import com.lwh.util.SmsConsumer;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsConsumer smsConsumer;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public User findByUser(User user) {
        User u = userMapper.findByUser(user);
        return u;
    }

    @Override
    public String sendCode(String phone) throws ClientException {
        // 6位验证码
        final String code = RandomStringUtils.randomNumeric(6);
        // 保存验证码并且设置过期时间
        redisTemplate.boundValueOps(phone).set(code);
        redisTemplate.boundValueOps(phone).expire(5, TimeUnit.MINUTES);
        User user = new User();
        String phoneCode = (String) redisTemplate.opsForValue().get(phone);
        String phoneCode2 = (String) redisTemplate.opsForValue().get(phone);
        System.out.println(phoneCode);
        System.out.println(phoneCode2);
        System.out.println("code"+code);
        System.out.println(phone);
        Map<String, String> map = new HashMap<String, String>();
        map.put("phoneNumbers", phone);
        // 短信签名
        map.put("signName", "输入短信签名");
        // 短信模板
        map.put("templateCode", "输入短信模板");
        map.put("templateParam", "{\"code\":\""+code+"\"}");
        String result = smsConsumer.readMessageForMap(map);
        return result;

    }

    @Override
    public User findByPhone(String phone, String code) {
        System.out.println(phone);
        String phoneCode = (String) redisTemplate.opsForValue().get(phone);
        System.out.println(phoneCode);
        if (code != null && !"".equals(code) && phoneCode != null && code.equals(phoneCode)) {
            // 验证码正确的
            User user = userMapper.findByPhone(phone);
            return user;

        } else {
            throw new RuntimeException("您输入的验证码不正确");
        }
    }
}
